////////////////////////////////////////////////////////////////////////////////
//
//  The MIT License
//
//  Copyright (c) 2008 - 2009. Dimarik
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////

package ru.goodcore.utils
{

import flash.utils.ByteArray;

public function traceByteArray(ba:ByteArray, position:uint = 0, length:uint = 0):String {
	//trace("==== START TRACE BYTEARRAY ====");

	var pos:	uint = ba.position;

	ba.position = position;

	if (length == 0) {
		length = ba.length - position;
	}

	var out:	String = '';

	var i:			uint = 0;
	var ascii:		String;
	var byte:		uint;
	var hex:		String;
	var hexLine:	String;

	while (length) {
		out += setNumLen(ba.position, 8) + 'h: ';
		ascii = '';
		hexLine = '';

		for (i = 0; i < 16 && length; i++) {
			byte = ba.readUnsignedByte();

			hex = byte.toString(16).toUpperCase();
			hex = hex.length < 2 ? '0' + hex : hex;

			hexLine += hex + ' ';

			ascii += byte > 31 ? String.fromCharCode(byte) : '.';
			length--;
		}

		while (hexLine.length < 48) {
			hexLine += ' ';
		}

		out += hexLine + '; ' + ascii;
		out += length ? '\n' : '';
	}

	ba.position = pos;

	//trace("===== END TRACE BYTEARRAY =====");

	return out;

	function setNumLen(value:uint, len:uint):String {
		var s:String = value.toString(16);
		while (s.length < len) s = '0' + s;
		return s;
	}
}
}